//=============================================================
// 创建人:            admin
// 创建时间:          2024/8/25
// 邮箱：             admin@example.com
//==============================================================
using LF.Common;
using LF.Domain.Entities;
using LF.Domain.Helper;

namespace LF.Domain.Services.Iml
{
    public class DictManagerService : IDictManagerService
    {
        #region 字典类型管理
        /// <summary>
        /// 获取字典类型列表
        /// </summary>
        public List<DictType> GetDictTypeList(int index, int pageSize, string? name, string? code)
        {
            var query = FreeSqlHelper.DbContext.Queryable<DictType>()
                .Where(p => !p.IsDelete);

            if (!name.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Name.Contains(name!));
            }

            if (!code.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Code.Contains(code!));
            }

            var list = query
                .OrderByDescending(p => p.CreatTime)
                .Page(index, pageSize)
                .ToList();

            return list;
        }

        /// <summary>
        /// 获取字典类型总数
        /// </summary>
        public long CountDictType(string? name, string? code)
        {
            var query = FreeSqlHelper.DbContext.Queryable<DictType>()
                .Where(p => !p.IsDelete);

            if (!name.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Name.Contains(name!));
            }

            if (!code.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Code.Contains(code!));
            }

            var count = query.Count();
            return count;
        }

        /// <summary>
        /// 获取字典类型详情
        /// </summary>
        public DictType GetDictType(Guid id)
        {
            var item = FreeSqlHelper.DbContext.Queryable<DictType>()
                .Where(p => p.Id == id)
                .First();
            return item;
        }

        /// <summary>
        /// 新增字典类型
        /// </summary>
        public bool InsertDictType(DictType dictType)
        {
            var result = FreeSqlHelper.DbContext.Insert(dictType).ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 更新字典类型
        /// </summary>
        public bool UpdateDictType(DictType dictType)
        {
            var result = FreeSqlHelper.DbContext.Update<DictType>(dictType.Id)
                .SetSource(dictType)
                .ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 删除字典类型
        /// </summary>
        public bool DeleteDictType(Guid id)
        {
            var result = FreeSqlHelper.DbContext.Delete<DictType>(id).ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 获取所有字典类型
        /// </summary>
        public List<DictType> GetAllDictType()
        {
            var list = FreeSqlHelper.DbContext.Queryable<DictType>()
                .Where(p => !p.IsDelete)
                .OrderByDescending(p => p.CreatTime)
                .ToList();
            return list;
        }
        #endregion

        #region 字典项管理
        /// <summary>
        /// 获取字典项列表
        /// </summary>
        public List<DictItem> GetDictItemList(int index, int pageSize, Guid typeId, string? label, string? value)
        {
            var query = FreeSqlHelper.DbContext.Queryable<DictItem>()
                .LeftJoin<DictType>((i, t) => i.TypeId == t.Id)
                .Include(i => i.Type)
                .Where(p => !p.IsDelete && p.TypeId == typeId);

            if (!label.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Label.Contains(label!));
            }

            if (!value.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Value.Contains(value!));
            }

            var list = query
                .OrderBy(p => p.OrderNo)
                .Page(index, pageSize)
                .ToList();

            return list;
        }

        /// <summary>
        /// 获取字典项总数
        /// </summary>
        public long CountDictItem(Guid typeId, string? label, string? value)
        {
            var query = FreeSqlHelper.DbContext.Queryable<DictItem>()
                .Where(p => !p.IsDelete && p.TypeId == typeId);

            if (!label.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Label.Contains(label!));
            }

            if (!value.IsNullOrWhiteSpace())
            {
                query = query.Where(p => p.Value.Contains(value!));
            }

            var count = query.Count();
            return count;
        }

        /// <summary>
        /// 获取字典项详情
        /// </summary>
        public DictItem GetDictItem(Guid id)
        {
            var item = FreeSqlHelper.DbContext.Queryable<DictItem>()
                .LeftJoin<DictType>((i, t) => i.TypeId == t.Id)
                .Include(i => i.Type)
                .Where(p => p.Id == id)
                .First();
            return item;
        }

        /// <summary>
        /// 新增字典项
        /// </summary>
        public bool InsertDictItem(DictItem dictItem)
        {
            var result = FreeSqlHelper.DbContext.Insert(dictItem).ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 更新字典项
        /// </summary>
        public bool UpdateDictItem(DictItem dictItem)
        {
            var result = FreeSqlHelper.DbContext.Update<DictItem>(dictItem.Id)
                .SetSource(dictItem)
                .ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 删除字典项
        /// </summary>
        public bool DeleteDictItem(Guid id)
        {
            var result = FreeSqlHelper.DbContext.Delete<DictItem>(id).ExecuteAffrows();
            return result > 0;
        }
        #endregion
        
        #region 字典初始化方法
        /// <summary>
        /// 初始化切片方式字典
        /// </summary>
        /// <returns>是否成功</returns>
        public bool InitializeSliceTypeDict()
        {
            // 检查字典类型是否已存在
            var existingType = FreeSqlHelper.DbContext.Queryable<DictType>()
                .Where(p => p.Code == "slice_type" && !p.IsDelete)
                .First();

            if (existingType != null)
            {
                return false; // 字典类型已存在，不需要创建
            }

            bool success = false;
            FreeSqlHelper.DbContext.Transaction(() =>
            {
                try
                {
                    // 创建字典类型
                    var dictType = new DictType
                    {
                        Id = Guid.NewGuid(),
                        Name = "切片方式",
                        Code = "slice_type",
                        Status = 1, // 启用
                        Remark = "知识库文件切片方式",
                        CreatTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        Creator = DomainConfig.CurrentUserId
                    };
                    
                    FreeSqlHelper.DbContext.Insert(dictType).ExecuteAffrows();

                    // 创建字典项
                    var dictItems = new List<DictItem>
                    {
                        new DictItem
                        {
                            Id = Guid.NewGuid(),
                            Label = "固定长度",
                            Value = "0",
                            TypeId = dictType.Id,
                            OrderNo = 1,
                            Status = 1, // 启用
                            Remark = "按固定长度切片",
                            CreatTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Creator = DomainConfig.CurrentUserId
                        },
                        new DictItem
                        {
                            Id = Guid.NewGuid(),
                            Label = "QA问答",
                            Value = "1",
                            TypeId = dictType.Id,
                            OrderNo = 2,
                            Status = 1, // 启用
                            Remark = "按QA问答方式切片",
                            CreatTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Creator = DomainConfig.CurrentUserId
                        },
                        new DictItem
                        {
                            Id = Guid.NewGuid(),
                            Label = "段落",
                            Value = "2",
                            TypeId = dictType.Id,
                            OrderNo = 3,
                            Status = 1, // 启用
                            Remark = "按段落切片",
                            CreatTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            Creator = DomainConfig.CurrentUserId
                        }
                    };
                    
                    FreeSqlHelper.DbContext.Insert(dictItems).ExecuteAffrows();

                    success = true;
                }
                catch
                {
                    success = false;
                    throw;
                }
            });

            return success;
        }
        #endregion
    }
} 